package com.qdxwx.web.controller.auth;


import com.qdxwx.captcha.Constants;
import com.qdxwx.captcha.Producer;
import com.qdxwx.captcha.config.CaptchaConfig;
import com.qdxwx.web.controller.BaseController;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

/**
 * 图片验证码（支持算术形式）
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/auth/captcha")
public class CaptchaController extends BaseController {
    /**
     * 验证码生成
     */
    @GetMapping(value = {"/text","/char"})
    public void textCaptchaImage(HttpServletRequest request, HttpServletResponse response) {
        showCaptchaImage(request, response, "text");
    }

    @GetMapping(value = "/math")
    public void mathCaptchaImage(HttpServletRequest request, HttpServletResponse response) {
        showCaptchaImage(request, response, "math");
    }

    private void showCaptchaImage(HttpServletRequest request, HttpServletResponse response, String type) {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        try (ServletOutputStream out = response.getOutputStream()) {
            String capStr;
            String code;
            Producer captchaProducer;
            if ("math".equals(type)) {
                captchaProducer = CaptchaConfig.getMath();
                String capText = captchaProducer.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
            } else {
                captchaProducer = CaptchaConfig.getText();
                capStr = captchaProducer.createText();
                code = capStr;
            }
            BufferedImage bi = captchaProducer.createImage(capStr);
            HttpSession session = request.getSession();
            session.setAttribute(Constants.CAPTCHA_SESSION_KEY, code);
            //System.out.println("验证码：" + code);
            session.setMaxInactiveInterval(300);
            ImageIO.write(bi, "jpg", out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}